﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using log4net;
using System.Collections;
using System.IO;


namespace Iudicium.Utilitarios
{
    /// <summary>
    /// Descripción breve de Utilitarios
    /// </summary>
    public class Utilitarios
    {
        private static readonly ILog log = LogManager.GetLogger("LogFile");
        private static Hashtable theMimeTypeList = null;

        public Utilitarios()
        {

        }

        public static string Encriptar(string value)
        {
            SHA1 sha1 = SHA1Managed.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = sha1.ComputeHash(encoding.GetBytes(value));
            for (int i = 0; i < stream.Length; i++)
                sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }

        public static string GetFileMIMEType(string extension)
        {
            if (string.IsNullOrEmpty(extension))
            {
                log.Warn("Called GetFileMIMEType with null or empty extension");
                return null;
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("Trying to determine the MIME type for extension " + extension);
            }

            if (theMimeTypeList == null || theMimeTypeList.Count == 0)
            {
                log.Debug("The mime list was not loaded before.  Loading it for the first time");

                theMimeTypeList = new Hashtable();
                try
                {
                    // Load the MIME file list to memmory
                    using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("~/Resources/MIMETypes.txt")))
                    {
                        String line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (log.IsDebugEnabled)
                            {
                                log.Debug("Read a line from the MIME file: " + line);
                            }

                            if (line == null)
                            {
                                log.Debug("Empty line.  Will ignore it");
                                continue;
                            }

                            line = line.Trim();

                            // Ignore blank lines
                            if (string.IsNullOrEmpty(line))
                            {
                                log.Debug("Blank line. Will ignore it.");
                                continue;
                            }

                            // Ignore comment lines
                            if (line.StartsWith("#"))
                            {
                                log.Debug("Comment line. Will ignore it");
                                continue;
                            }

                            string[] typeComponents = line.Split(new char[] { ',' });

                            // Ignore lines that dont have two components
                            if (typeComponents.Length != 2)
                            {
                                log.Debug("The line does not not have two components exactly.  Will ignore it");
                                continue;
                            }

                            string fileExtension = typeComponents[0].Trim();
                            string mimeType = typeComponents[1].Trim();

                            // Ignore extensions that don't start with a period
                            if (!extension.StartsWith("."))
                            {
                                log.Warn("The extension " + fileExtension +
                                    " in MIME file does not start with a period.  Will ignore it");
                                continue;
                            }

                            if (theMimeTypeList.ContainsKey(fileExtension.ToUpper()))
                            {
                                log.Warn("The extension " + fileExtension +
                                    " is defined mmore than once in the MIME file types file. Will use only first one");
                                continue;
                            }

                            // We seem to have a good line.  Add it to the list.
                            if (log.IsDebugEnabled)
                            {
                                log.Debug("Adding \"" + fileExtension + "\" extension with MIME type \"" + mimeType +
                                    "\" to our list of MIME types");
                            }

                            theMimeTypeList.Add(fileExtension.ToUpper(), mimeType);
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Error("Failed to read the MIME type file", e);
                }

                log.Debug("Done loading MIME types from MIME types file");
            }

            // Now try to get the MIME type for the extension provided.
            if (!theMimeTypeList.ContainsKey(extension.ToUpper()))
            {
                log.Debug("We could not find the extension \"" + extension + "\" in our list");
                return null;
            }
            else
            {
                string mimeTypeFound = theMimeTypeList[extension.ToUpper()].ToString();

                if (log.IsDebugEnabled)
                {
                    log.Debug("Found mime type \"" + mimeTypeFound + "\" for extension \"" +
                        extension + "\" in the MIME Types list");
                }

                return mimeTypeFound;
            }
        }

        public static byte[] GetBytesFromFile(string fullFilePath)
        {
            // this method is limited to 2^32 byte files (4.2 GB)

            FileStream fs = File.OpenRead(fullFilePath);
            try
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return bytes;
            }
            finally
            {
                fs.Close();
            }

        }

        public static bool EliminarArchivo(int id)
        {
            bool result = false;
            string path = "";
            try
            {
                path = Iudicium.Archivos.CRN.ArchivoCRN.EliminarArchivo(id);
                result = true;
            }
            catch (Exception ex)
            {
                log.Error("Ocurrio un error al eliminar el archivo de la base de datos", ex);
            }

            System.IO.FileInfo fileInfoObject = new System.IO.FileInfo(path);
            if (fileInfoObject.Exists)
            {
                try
                {
                    fileInfoObject.Delete();
                }
                catch (Exception ex)
                {
                    log.Error("No se pudo borrar el archivo '" + path + "'. Borrar a mano", ex);
                }
            }
            return result;
        }
    }
}
